<?php


namespace app\crm\model;

use think\facade\Db;
use app\admin\model\Common;

class Setting extends Common
{

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'setting';

    /**
     * 列表
     * @param  array $request 请求参数
     * @return array
     */
    public function getDataList(array $request): array
    {
        try {
            $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
            $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
            $name       = isset($request['name']) && trim($request['name']) ? trim($request['name']) : '';
            $categoryId = isset($request['category_id']) && intval($request['category_id']) ? intval($request['category_id']) : 0;
            $where      = [];
            $name && array_push($where, ['name', 'like', '%'.$name.'%']);
            $categoryId && array_push($where, ['category_id', '=', $categoryId]);
            array_push($where, ['status', '=', 1]);
            array_push($where, ['category_id', '<>', 7]);
            // print_r($where);exit();
            $dataCount = $this->where($where)->count();
            if ($dataCount) {
                $field = ['id', 'name', 'status', 'category_id', 'create_time', 'update_time'];
                $list  = $this->where($where)->field($field)->order('id ASC')
                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->select()->toArray();
                $categoryIdArr = array_unique(array_column($list, 'category_id'));
                $categoryList  = Db::name('setting_category')->where('id', 'in', $categoryIdArr)->column('name', 'id');
                foreach ($list as $key => $val) {
                    $list[$key]['category_name'] = $categoryList[$val['category_id']] ?? '';
                }
            }

            $data              = [];
            $data['list']      = $list ?? [];
            $data['dataCount'] = $dataCount ?? 0;
            return $data;
        } catch (\Exception $e) {
        }

        $this->error = '暂无此数据';
        return [];
    }

    /**
     * 添加
     * @param  array $request 请求参数
     * @return bool
     */
    public function addData(array $request): bool
    {
        try {
            $validate = new \app\crm\validate\Setting();
            if (!$validate->scene('create')->check($request)) {
                $this->error = $validate->getError();
                return false;
            }

            $data = [
                'category_id' => intval($request['category_id']),
                'name'        => trim($request['name']),
                'status'      => intval($request['status']),
                'create_time' => time(),
                'update_time' => time()
            ];
            $settingId = $this->insertGetId($data);
            if ($settingId) {
                $this->error = '添加成功';
                return true;
            }
        } catch (\Exception $e) {
        }

        $this->error = '添加失败';
        return false;
    }

    /**
     * 编辑
     * @param  array $request 请求参数
     * @return bool
     */
    public function saveData(array $request): bool
    {
        try {
            $userId   = $request['user_id'] ?? 0;
            $validate = new \app\crm\validate\Setting();
            if (!$validate->scene('update')->check($request)) {
                $this->error = $validate->getError();
                return false;
            }

            $settingId = $request['id'];
            $field     = ['name', 'category_id', 'status'];
            $info      = $this->where(['id' => $settingId])->field($field)->find();
            if (!$info) {
                $this->error = '信息不存在';
                return false;
            }

            $data = [
                'category_id' => intval($request['category_id']),
                'name'        => trim($request['name']),
                'status'      => intval($request['status']),
                'update_time' => time()
            ];
            $bool = $this->where(['id' => $settingId])->update($data);
            if ($bool) {
                $this->error = '编辑成功';
                return true;
            }
        } catch (\Exception $e) {
        }

        $this->error = '编辑失败';
        return false;
    }

    /**
     * 删除
     * @param  array $request 请求参数
     * @return bool
     */
    public function deleteData(array $request): bool
    {
        try {
            $settingId = $request['id'] ?? 0;
            if (!$settingId) {
                $this->error = '参数错误';
                return false;
            }

            $list = $this->where('id', '=', $settingId)->select()->toArray();
            if (!$list) {
                $this->error = '请选择数据';
                return false;
            }

//            这里需要判断是否被用、如果被用到则不能删除

            $bool = $this->where('id', '=', $settingId)->delete();
            if ($bool) {
                $this->error = '删除成功';
                return true;
            }
        } catch (\Exception $e) {
        }

        $this->error = '删除失败';
        return false;
    }

    /**
     * 状态
     * @param  array $request 请求参数
     * @return bool
     */
    public function statusData(array $request): bool
    {
        try {
            $settingId = $request['id'] ?? 0;
            $status    = isset($request['status']) && intval($request['status']) ? intval($request['status']) : 0;
            if (!$settingId || !in_array($status, [1, 2])) {
                $this->error = '参数错误';
                return false;
            }

            $list = $this->where('id', '=', $settingId)->select()->toArray();
            if (!$list) {
                $this->error = '请选择数据';
                return false;
            }
            $updateData   = [
                'status'      => $status,
                'update_time' => time()
            ];
            $bool = $this->where('id', '=', $settingId)->update($updateData);
            if ($bool) {
                $this->error = '更新成功';
                return true;
            }
        } catch (\Exception $e) {
        }

        $this->error = '更新失败';
        return false;
    }

    /**
     * 全部
     * @param  array $request 请求参数
     * @return array
     */
    public function getAllDataList(array $request): array
    {
        try {
            $name   = isset($request['name']) && trim($request['name']) ? trim($request['name']) : '';
            $status = isset($request['status']) && intval($request['status']) ? intval($request['status']) : 0;
            $where  = [];
            $status && array_push($where, ['s.status', '=', $status]);
            $field = ['s.id', 's.name', 's.category_id', 'c.name' => 'category_name', 'c.key'];
            $list  = $this->alias('s')
                ->join('setting_category c', 's.category_id = c.id', 'LEFT')
                ->where($where)->field($field)->order('id DESC')
                ->select()->toArray();
            $data = [];
            foreach ($list as $key => $val) {
                $value = [
                    'id'   => $val['id'],
                    'name' => $val['name']
                ];
                if (!isset($data[$val['key']])) {
                    $data[$val['key']] = [
                        'name' => $val['category_name'],
                        'data' => [$value]
                    ];
                } else {
                    $data[$val['key']]['data'][] = $value;
                }
            }

            return $data ?? [];
        } catch (\Exception $e) {
        }

        $this->error = '暂无此数据';
        return [];
    }

    /**
     * 列表
     * @param  array $request 请求参数
     * @return array
     */
    public function settingInfo(array $request): array
    {
        try {
            $id                = $request['id'] ?? 0;
            $info              = $this->where([['id','=',$id]])->find()->toArray();
            $data              = [];
            $data['info']      = $info ?? [];
            return $data;
        } catch (\Exception $e) {
        }

        $this->error = '暂无此数据';
        return [];
    }

    /**
     * 获取标签数据
     */
    public function read_member_label(array $request): array
    {
        $where = [];
        array_push($where,['pid','=',0]);
        array_push($where,['category_id','=',7]);
        $list  = $this -> where($where) ->order('id desc') ->  select() -> toArray(); 
		
        foreach($list as $key => $val){
            $one  = $this -> where('pid','=',$val['id']) -> select() -> order('id desc') -> toArray();
            $list[$key]['children'] = $one;
        }		
        $data              = [];
        $data['list']      = $list ?? [];
        return $data;
    }
    
    /**
     * 新增标签数据
     */
    public function add_member_label(array $request): array
    {
        $add = [];
        $add['name'] = $request['name'] ?? '';
        $add['category_id'] = 7;
        $add['create_time'] = time();
        $add['update_time'] = time();
        $add['pid'] = $request['pid'] ?? 0;
        if (empty($add['name'])) {
            $this->error = '标签名称不能为空';
            return [];
        }
        if ($add['pid'] > 0) {
            $list  = $this -> where('id','=',$add['pid']) -> find();
            if (!$list) {
                $this->error = '上级标签不存在';
                return [];
            }
            if ($list['category_id'] <> 7) {
                $this->error = '上级标签类型错误';
                return [];
            }
        }
        $settingId = $this->insertGetId($add);
        $data = ['id'=>$settingId];
        return $data;
    }
    
    /**
     * 获取标签详情
     */
    public function read_member_label_info(array $request): array
    {
        $id = $request['id'] ?? 0;
        if ($id == 0) {
            $this->error = '标签数据不存在';
            return [];
        }
        $find = $this->where('id','=',$id)->find();
        if (!$find) {
            $this->error = '标签数据不存在';
            return [];
        }
        $sfind = $this->where('pid','=',$find['id'])->find();
        $find['superior'] = $sfind ?? [];
        $data = ['info'=>$find];
        return $data;
    }
    
    /**
     * 新增标签数据
     */
    public function save_member_label(array $request): array
    {
        $save = [];
        $save['name'] = $request['name'] ?? '';
        $save['update_time'] = time();
        $save['pid'] = $request['pid'] ?? 0;
        $id = $request['id'] ?? 0;
        if ($id == 0) {
            $this->error = '需要编辑的标签不存在';
            return [];
        }
        if (empty($save['name'])) {
            $this->error = '标签名称不能为空';
            return [];
        }
        if ($save['pid'] > 0) {
            $list  = $this -> where('id','=',$save['pid']) -> find();
            if (!$list) {
                $this->error = '上级标签不存在';
                return [];
            }
            if ($list['category_id'] <> 7) {
                $this->error = '上级标签类型错误';
                return [];
            }
        }
        $this->where('id','=',$id)->update($save);
        $data = ['id'=>$id];
        return $data;
    }
    
    public function getTwoLabel(array $request): array
    {
        $list = $this->where([['category_id','=',7],['pid','>',0]])->field('id,name')->select()->toArray();
        return $list;
    }
}
